﻿using System;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using VPLink2013.Framework;
using VPLink2013.Framework.Extensions;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Text;
using System.Collections.Specialized;


namespace VPLink2014
{
    public partial class Quizz : LayoutsPageBase
    {
        private string _cachPath = string.Empty;
        private ConfigQuizz config;

        protected void Page_Load(object sender, EventArgs e)
        {
            string responseJson = "{}";
            GetGonfigs();
            try
            {
                if (!string.IsNullOrEmpty(this.Request.QueryString["SaveUserAnswer"])
                    && !string.IsNullOrEmpty(this.Request.QueryString["QuizzTitle"])
                    && !string.IsNullOrEmpty(this.Request.QueryString["Reponse"]))
                {
                    // Display Answer
                    // Save answer
                    string quizTitle = this.Request.QueryString["QuizzTitle"];
                    string encodedTitleISO = HttpUtility.UrlEncode(quizTitle, Encoding.GetEncoding("ISO-8859-1"));
                    string decodedTitleISO = HttpUtility.UrlDecode(encodedTitleISO, Encoding.GetEncoding("ISO-8859-1"));
                    string reponse = this.Request.QueryString["Reponse"];
                    bool saved = QuizzMapper.SaveQuizzAnswer(SPContext.Current.Site.Url, config.quizzList.url, Context.User.Identity.Name, decodedTitleISO, reponse);
                    responseJson = string.Format(@"{{""userHasAnswered"" : ""{0}""}}", saved.ToString().ToJson());
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.Request.QueryString["CheckUserAnswered"])
                    && !string.IsNullOrEmpty(this.Request.QueryString["QuizzTitle"]))
                    {
                        // Display quizz if user has never answered to quizz
                        string quizTitle = this.Request.QueryString["QuizzTitle"];
                        string encodedTitleISO = HttpUtility.UrlEncode(quizTitle, Encoding.GetEncoding("ISO-8859-1"));
                        string decodedTitleISO = HttpUtility.UrlDecode(encodedTitleISO, Encoding.GetEncoding("ISO-8859-1"));

                        bool userHasAnswered = QuizzMapper.CheckIfUserAlreadyAnswered(SPContext.Current.Site.Url, config.quizzList.url, Context.User.Identity.Name, decodedTitleISO);
                        responseJson = string.Format(@"{{""userHasAnswered"" : ""{0}""}}", userHasAnswered.ToString().ToJson());
                    }
                }
                Response.Write(responseJson);
                Response.End();
            }

            catch (System.Threading.ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                responseJson = string.Format(@"{{""messageError"" : ""{0}"", ""stackTrace"" : ""{1}""}}", ex.Message.ToJson(), ex.StackTrace.ToJson());
                Response.Write(responseJson);
                Response.End();
            }
        }

        private void GetGonfigs()
        {
            string relativeDir = this.AppRelativeTemplateSourceDirectory
                         .Replace(@"~/_layouts", @"TEMPLATE/LAYOUTS")
                         .Replace(@"/", @"\");

            relativeDir = relativeDir.Substring(0, relativeDir.IndexOf("ApplicationPages"));
            string adsPathDir = SPUtility.GetVersionedGenericSetupPath(relativeDir, 15);
            string _configPath = string.Format("{0}{1}", adsPathDir, @"Config\quizz.config.xml");
            string _cachePath = string.Format("{0}{1}", adsPathDir, @"Cache\quizz.xml");
            config = FileSerialization.CreateObjFromXML<ConfigQuizz>(_configPath);

            //if( FileSerializationManager.CheckFileCacheExists( _cachePath ) )
            //{
            //    cachedQuizz = FileSerializationManager.CreateObjFromXML<QuizzCache>( _cachePath );
            //}
        }
    }
}
